package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.mapper.MenuMapper;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {

    @Autowired
    MenuMapper mapper;

    @Override
    public int insert(Menu record) {
        return mapper.insert(record);
    }

    @Override
    public Menu selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Menu> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Menu record) {
        return mapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Menu> selectRootMenu() {
        return mapper.selectRootMenu();
    }

    @Override
    public List<Long> selectByRoleId(Long roleId) {
        return mapper.selectByRoleId(roleId);
    }

    @Override
    public List<Menu> selectEmployeeMenu() {
        //1.获取所有的菜单
        List<Menu> menus = mapper.selectRootMenu();
        //2.获取当前登陆用户
        Employee currentUser = UserContext.getCurrentUser();
        //3.判断是否是管理员
        if (!currentUser.getAdmin()) {
            //4.获取当前用户拥有的菜单id集合
            List<Long> ids = mapper.selectByEmployeeId(currentUser.getId());
            //5.检查权限
            checkPermission(menus,ids);
        }
        return menus;
    }

    public void checkPermission(List<Menu> menus,List<Long> ids){
        //1.遍历菜单,如果当前用户没有权限访问的菜单,直接从集合中移除掉
        Iterator<Menu> iterator = menus.iterator();
        while (iterator.hasNext()) {
            Menu menu = iterator.next();
            //判断菜单id是否存在用户拥有的菜单集合中
            if (!ids.contains(menu.getId())) {
                iterator.remove();
                continue;
            }
            //递归判断子菜单
            if(menu.getChildren().size()>0){
                checkPermission(menu.getChildren(),ids);
            }
        }
    }
}
